package com.anlu.base.jdbc.config;

import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
public class JdbcDataSourceConfig {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Bean("ds1Properties")
    @Primary
    @ConfigurationProperties("db.datasource.ds1")
    public DataSourceProperties ds1Properties(){
        logger.info("init datasource1 success");
        return new DataSourceProperties();
    }

    @Bean("ds1")
    @Primary
    @ConfigurationProperties("db.datasource.ds1.configuration")
    public HikariDataSource ds1(@Qualifier("ds1Properties") DataSourceProperties properties) {
        HikariDataSource build = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        build.setPoolName("ds1");
        return build;
    }


    /**
     * 声明事务管理器
     * @param dataSource
     * @return
     */
    @Bean(name = "tx1")
    @Primary
    public PlatformTransactionManager tx1(@Qualifier("ds1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
